package zookeeper;

//zijixie
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;

/**zookeeper
 * 监听节点或者子节点value值变化
 */

public class JT {
    ZooKeeper OK = null;

    @Before
    public void init() throws IOException {
                                                                                                //sessionTimeout时间设定测试时候可以大一点
        OK = new ZooKeeper("192.168.88.200:2181,192.168.88.201:2181,191.168.88.202:2181,2000", 20000, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                if (event.getState() == Event.KeeperState.SyncConnected && event.getType() == Event.EventType.NodeDataChanged) {
                    System.out.println(event.getPath());  //收到事件发生的节点路径
                    System.out.println(event.getType());  //收到发生事件的类型
                    System.out.println("发生变化_______");//收到事件后处理的逻辑

                    try {
                        OK.getData("/a", true, null);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }else if (event.getState() == Event.KeeperState.SyncConnected && event.getType() == Event.EventType.NodeChildrenChanged) {
                    System.out.println(event.getPath());
                    System.out.println(event.getType());
                    System.out.println("子节点发生变化");

                    try {
                        OK.getChildren("a/aa",true,null);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
        });
    }
    @Test
    public void  testGetWatch() throws Exception{
        byte [] data = OK.getData("/a", true, null);                  //监听节点数据变化
    //    byte[] data = OK.getData("/a/aa", true, null);//监听节点下的子节点数据变化
       System.out.println(new String(data ,"UTF-8"));
        Thread.sleep(Long.MAX_VALUE);
    }

}